<?php
/**
 *  @author  blues
 *  @version 1.0
 *  @package avatar
 */

class Avatar extends CInputWidget
{
    public $uploadurl   = '.';  //项目根目录
    public $upload      = '/uploads/'; //上传文件存放根文件夹
    public $savepath    = ''; //前台传过来的文件保存路径
    public $max_size    = 100000; //文件的最大size

    public $fileElementName = ''; //前台ajaxfileupload传过来的file控件ID
    public $file_ext        = 'image'; //上传文件的类型
    public $type            = 'file'; //生成不同类型的文件夹

    public $iscut   = false; //是否对上传图片进行裁剪
    public $thumbname = 'avatar'; //裁剪后图片的名字
    public $cutsize = array('big'=>array(112,112),'middle'=>array(48,48),'small'=>array(36,36),'micro'=>array(24,24)); //裁剪的不同size

    public function getPath()
    {
        $baseDir = dirname(__FILE__);
        return Yii::app()->getAssetManager()->publish($baseDir);
    }

    /**
     * Initialize the widget
     */
    public function init()
    {
        /*$path = $this->getPath();
        $cs = Yii::app()->getClientScript();
        $cs->registerScriptFile($path.'js/jquery-1.8.2.min.js');
        $cs->registerScriptFile($path.'js/ajaxfileupload.js');*/
    }

    /*
     * 上传文件方法
     */
    public function Fileupload()
    {
        $file_ext = $this->file_ext;
        $type     = $this->type;
        // 获取图片路径信息
        $getuploadurl = $this->getUploadUrl($this->savepath,$file_ext,$type);

        //最大文件大小
        $max_size = $this->max_size;

        $error = "";
        $msg = "";
        $filename = "";
        $filesize = "";

        $fileElementName = $this->fileElementName;
        if(!empty($_FILES[$fileElementName]['error']))
        {
            switch($_FILES[$fileElementName]['error'])
            {
            case '1':
                $error = '超过php.ini允许的大小。';
                break;
            case '2':
                $error = '超过表单允许的大小。';
                break;
            case '3':
                $error = '图片只有部分被上传。';
                break;
            case '4':
                $error = '请选择图片。';
                break;
            case '6':
                $error = '找不到临时目录。';
                break;
            case '7':
                $error = '写文件到硬盘出错。';
                break;
            case '8':
                $error = 'File upload stopped by extension。';
                break;
            case '999':
            default:
                $error = '未知错误。';
            }
        } elseif(empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none') {
            $error = '请选择上传文件';
        } else {
            $file_ext = pathinfo($_FILES[$fileElementName]['name'], PATHINFO_EXTENSION);
            $filesize = @filesize($_FILES[$fileElementName]['tmp_name']);
            if($this->iscut)
                $filename = $getuploadurl['filename_path'].$this->thumbname.'.'.$file_ext;
            else
                $filename = $getuploadurl['filename_path'].date("YmdHis").'_'.rand(10000, 99999).'.'.$file_ext;

            if($filesize > $max_size) {
                //检查文件大小
                $error = "上传文件大小超过限制。";
            } elseif (in_array($file_ext, $getuploadurl['ext_arr']) === false) {
                //检查扩展名
                $error = "上传文件扩展名是不允许的扩展名。只允许" . implode(",", $getuploadurl['ext_arr']) . "格式。";
            } else {
                if(move_uploaded_file($_FILES[$fileElementName]["tmp_name"], $getuploadurl['uploadurl'].$filename) === false) {
                    $error = "上传失败！！！";
                } else {
                    @unlink($_FILES[$fileElementName]);
                    //裁剪图片 
                    if($this->iscut){
                        foreach($this->cutsize as $key=>$value){
                            $thumbname = $this->uploadurl.$getuploadurl['filename_path'].$this->thumbname.'_'.$key;
                            $this->getIcon($getuploadurl['uploadurl'].$filename,$value[0],$value[1],$thumbname);
                        }
                    }
                }
            }
        }

        $file_name = $getuploadurl['filename_path'].pathinfo($filename, PATHINFO_FILENAME);
        $file_ext = pathinfo($filename, PATHINFO_EXTENSION);

        echo "{";
        echo 	"error: '" . $error . "',\n";
        echo    "msg: {filename: '" . $filename . "', filesize: '" . $filesize . "', file_name: '" . $file_name . "', file_ext: '" . $file_ext . "'}\n";
        echo "}";
    }

    //裁剪图片 getIcon 参数 $src_img:图片路径，$dst_w:设定的宽度，$dst_h:设定的高度
    public function getIcon($src_img,$dst_w,$dst_h,$thumbname){
        list($src_w,$src_h) = getimagesize($src_img);  // 获取原图尺寸 
        $dst_scale = $dst_h/$dst_w; //目标图像长宽比
        $src_scale = $src_h/$src_w; // 原图长宽比 

        if($src_scale>=$dst_scale)
        {  
            // 过高
            $w = intval($src_w);
            $h = intval($dst_scale*$w);
            $x = 0;
            $y = ($src_h - $h)/3;
        }
        else
        { 
            // 过宽
            $h = intval($src_h);
            $w = intval($h/$dst_scale);
            $x = ($src_w - $w)/2;
            $y = 0;
        }
        // 剪裁
        $imagetype = pathinfo($src_img, PATHINFO_EXTENSION);
        $source = "";
        if($imagetype=='gif')
            $source = imagecreatefromgif($src_img);
        elseif($imagetype=='jpg' || $imagetype=='jpeg')
            $source = imagecreatefromjpeg($src_img);
        elseif($imagetype=='png')
            $source = imagecreatefrompng($src_img);
        $croped = imagecreatetruecolor($w, $h);
        imagecopy($croped,$source,0,0,$x,$y,$src_w,$src_h);
        // 缩放
        $scale = $dst_w/$w;
        $target = imagecreatetruecolor($dst_w, $dst_h);
        $final_w = intval($w*$scale);
        $final_h = intval($h*$scale);
        imagecopyresampled($target,$croped,0,0,0,0,$final_w,$final_h,$w,$h);
        // 保存 
        $newname = $thumbname.'.'.$imagetype;
        if($imagetype=='gif')
            imagegif($target, $newname);
        elseif($imagetype=='jpg' || $imagetype=='jpeg')
            imagejpeg($target, $newname);
        elseif($imagetype=='png')
            imagepng($target, $newname);
        imagedestroy($target);
    }

    /*
     * 获取文件上传路径
     */
    public function getUploadUrl($upload_ext,$file_ext,$type='file')
    {
        $uploadurl  = $this->uploadurl;
        $upload     = $this->upload;

        $uploads = $uploadurl.$upload;
        if (!file_exists($uploads)) {
            //检查目录写权限
            if (@is_writable($uploads) === false) {
                @chmod($uploads, 0777);
            }
            mkdir($uploads);
        }

        /* 上传文件路径 */
        $uploadpath = $uploads.$upload_ext;
        if (!file_exists($uploadpath)) {
            //检查目录写权限
            if (@is_writable($uploadpath) === false) {
                @chmod($uploadpath, 0777);
            }
            $aa = $this->mkdirs($uploadpath);
        }

        /* 最后一层日期目录 */
        if($type=='file'){
            $ymd = date("Ymd")."/";
        }else{
            $ymd = '';
        }

        $save_path = $uploadpath.$ymd;
        if (!file_exists($save_path)) {
            //检查目录写权限
            if (@is_writable($save_path) === false) {
                @chmod($save_path, 0777);
            }
            mkdir($save_path);
        }

        $filename_path = $upload.$upload_ext.$ymd;

        //定义允许上传的文件扩展名
        $ext_arr = array(
            'image' => array('gif', 'jpg', 'jpeg', 'png', 'bmp'),
            'flash' => array('swf', 'flv'),
            'media' => array('swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb'),
            'file' => array('doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2'),
        );

        return array(
            'uploadurl'         => $uploadurl,
            'filename_path'     => $filename_path,
            'ext_arr'           => $ext_arr[$file_ext],
        );
    }

    // 生成多级目录
    function mkdirs($dir)  
    {  
        if(!is_dir($dir))  
        {  
            if(!$this->mkdirs(dirname($dir))){  
                return false;
            }  
            if(!mkdir($dir,0777)){  
                return false;  
            }  
        }  
        return true;  
    }

}
?>
